<?php

namespace App\Admin\Console\Commands;

use App\Admin\Models\ApiDocument;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class ApidocMakeCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = '
        admin:make-apidoc
        {dir : 指定扫描目录}
    ';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '创建API文档';

    /**
     * 总记录数
     *
     * @var int
     */
    protected $total;

    /**
     * 成功的记录数
     *
     * @var int
     */
    protected $success;

    public function __construct()
    {
        $this->total = 0;
        $this->success = 0;
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $dir = $this->argument('dir');
        $this->searchfile($dir);
        if ($this->total == $this->success && $this->total>0) {
            $this->info("API文档创建成功");
            return true;
        } else {
            $this->error("API文档创建失败");
            return false;
        }
    }

    /**$x
     * 递归搜索文件
     * @param string $path 目录所在路径
     * @param int $deep 递归调用的深度 默认为0
     * @return string 输出当前目录及子目录的所有文件
     */
    function searchfile($path,$deep = 0)
    {
        if (!env('SHOWDOC_API_KEY')) {
            $this->error("请配置SHOWDOC_API_KEY");
        }
        if (!env('SHOWDOC_API_TOKEN')) {
            $this->error("请配置SHOWDOC_API_TOKEN");
        }
        $apiDocument = app(ApiDocument::class);
        # api_key
        $api_key = env('SHOWDOC_API_KEY');
        # api_token		
        $api_token = env('SHOWDOC_API_TOKEN');	
        # 同步到的url。使用www.showdoc.com.cn的不需要修改，使用私有版的请修改
        $url = env('SHOWDOC_DOMAIN')."/server/?s=/api/open/fromComments"; 
        $maxsize = 1024*1024*1;  # 1M以下的文本文件才会被扫描
        $dirHandle = opendir($path);
        while( false !== ($file = readdir($dirHandle)) ){
            if( $file != '.' && $file != '..'  ){
                //让文件输出更有层次感
                $chkfile = $path.'/'.$file;
                $filesize = filesize($chkfile);
                if ($filesize < $maxsize) {
                    $result = shell_exec("sed -n -e '/\/\*\*/,/\*\//p' $chkfile | grep showdoc");
                    if ($result) {
                        $txt = shell_exec("sed -n -e '/\/\*\*/,/\*\//p' $chkfile");
                        if (strstr($txt, '@url') && strstr($txt, '@title')) {
                            $this->total++;
                            DB::beginTransaction();
                            # 通过接口生成文档
                            $data['from'] = 'shell';
                            $data['api_key'] = $api_key;
                            $data['api_token'] = $api_token;
                            $data['content'] = $txt;
                            $generateRe = curl_post($url, $data);
                            $updateApiDocumentRe = $apiDocument->updateApiDocument($txt);
                            if (strstr($generateRe, '成功') && $updateApiDocumentRe) {
                                DB::commit();
                                $this->success++;
                            } else {
                                DB::rollBack();
                            }
                        }
                    }
                }
                //判断当前文件是否为目录
                if( is_dir($path . '/' . $file) ){
                    //递归点 递归调用遍历目录
                    $this->searchfile($path . '/' . $file, $deep + 1);
                }
            }
        }
        closedir($dirHandle);
    }
}